const Tag = require('../db/models/tag')
const { SuccessRes, ErrorRes } = require('../utils/res');

exports.getAll = async ctx => {
    const findResults = await Tag.find({})
    const total = findResults.length;
    return ctx.body = new SuccessRes({ result: {findResults, total},msg:'获取成功' })
  }

  exports.createOne = async (ctx) => {
    let { title} = ctx.request.body;
    let tag = { title};
    console.log(tag,'tag one')
    if (!title) {
      ctx.body = new ErrorRes({ code:401, msg: '必填选项不能为空!' })
    } else {
      let one = await Tag.find({ title: tag.title });
      
      if (one.length == 0) {
        let result = await Tag.create(tag);
        return ctx.body = new SuccessRes({ result, msg: '创建成功' })
      } else {
        return ctx.body = new ErrorRes({ code:401, msg: ',已存在相同的标签!' })
      }
    }
  }

  exports.deleteOne = async (ctx) => {
    let { id } = ctx.request.body;
    let tag = await Tag.findOne({ _id: id });
    if (!tag) {
      return ctx.body = new ErrorRes({ code:401, msg: ',没有找到该命令!' })
    }
    let result = await Tag.deleteOne({ _id: id });
    if (result) {
      result.msg = `删除名为${tag.title}的标签`
      return ctx.body = new SuccessRes({ result })
    } else {
      return ctx.body = new ErrorRes({ code:401, msg: ',删除失败!' })
    }
  }